package com.shxy.service.impl;

import com.shxy.controller.ui.EmployeeBean;
import com.shxy.dao.EmployeeDao;
import com.shxy.dao.EmployeeImportDao;
import com.shxy.entity.EmpImport;
import com.shxy.entity.Employee;
import com.shxy.entity.common.enums.GenderEnum;
import com.shxy.service.IEmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class EmployeeService implements IEmployeeService {
    @Autowired private EmployeeDao employeeDao;
    @Autowired private EmployeeImportDao employeeImportDao;

    @Override
    public Employee create(EmployeeBean employee) {
        Employee emp = new Employee();
        BeanUtils.copyProperties(employee, emp);
        return employeeDao.save(emp);
    }

    @Override
    public Page<Employee> query(EmployeeBean employee, int page, int size) {
        return employeeDao.findAll(PageRequest.of(page - 1, size));
    }

    @Override
    public boolean existsOfId(String id) {
        return employeeDao.findById(id).isPresent();
    }

    @Override
    public boolean existsOfIdCard(String idCard) {
        return employeeDao.findByIdCard(idCard).isPresent();
    }

    @Override
    public void update(EmployeeBean employee) {
        Employee emp = new Employee();
        BeanUtils.copyProperties(employee, emp);
        employeeDao.save(emp);
    }

    @Override
    public void deleteById(String id) {
    }

    @Override
    public List<Employee> importFromBase() {
        // 1、读取全部要导入的信息
        List<EmpImport> list = employeeImportDao.findAll();
        // 2、循环保存
        List<Employee> emps = list.stream().map(emp -> {
            Employee employee = new Employee();
            employee.setName(emp.getName());
            employee.setIdCard(emp.getIdCard());
            employee.setGender(Integer.parseInt(String.valueOf(emp.getIdCard().charAt(16))) % 2 != 0 ? GenderEnum.MAN : GenderEnum.WOMEN);

            return employee;
        }).collect(Collectors.toList());

        return employeeDao.saveAll(emps);
    }
}
